package com.example.blue;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import org.example.result.ZhenChanResult;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.PrimitiveIterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;

import lombok.ToString;


public class TestResActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener,DataProcessorManagerRight.DataUpdateListener{
    public Integer predictLabel=0;
    public Integer predictScore=0;
    public double[] displayFea;
    public Integer pred1ctLabe1=0;
    public Integer RTScore=0;
    public Integer PScore=0;
    public Integer PTScore=0;
    public Integer PTTScoreRTDisFea=0;
    public double[] RTDisFea ;
    public double[] PDisFea ;
    public double[] PTDisFea  ;
    public double[] PTTDisFea ;

    public Integer predictLabelR=0;
    public Integer predictScoreR=0;
    public double[] displayFeaR;
    public Integer pred1ctLabe1R=0;
    public Integer RTScoreR=0;
    public Integer PScoreR=0;
    public Integer PTScoreR=0;
    public Integer PTTScoreRTDisFeaR=0;
    public double[] RTDisFeaR ;
    public double[] PDisFeaR ;
    public double[] PTDisFeaR  ;
    public double[] PTTDisFeaR ;


    private DataProcessorManager processorManager;
    private BluetoothService bluetoothService;
    private String deviceId;
    private  ProgressDialog progressDialog;

    private TextView duizhi_jiaosudu;
    private TextView dakai_jiaosudu;
    private TextView bihe_jiaosudu;
    private TextView duizhi_cishu;
    private TextView yuce_label;
    private TextView yuce_score;

    private String duizhi_jiaosudu_str="0";
    private String dakai_jiaosudu_str="0";
    private String bihe_jiaosudu_str="0";
    private String duizhi_cishu_str="0";
    private String yuce_label_str="0";
    private String yuce_score_str="0";

    private String duizhi_jiaosudu_strR="0";
    private String dakai_jiaosudu_strR="0";
    private String bihe_jiaosudu_strR="0";
    private String duizhi_cishu_strR="0";
    private String yuce_label_strR="0";
    private String yuce_score_strR="0";

    private TextView zhenchan_lable;
    private TextView zhenchan_score;
    private TextView pingju_score;
    private TextView xiangxia_score;
    private TextView xiangnei_score;

    private TextView jingzhi_jizhiduan;
    private TextView jingzhi_jiaodu;
    private TextView jingzhi_pinglv;

    private TextView pingju_zhitiduan;
    private TextView pingju_jiaodu;
    private TextView pingju_pinglv;

    private TextView xiangxia_zhitiduan;
    private TextView xiangxia_jiaodu;
    private TextView xiangxia_pinglv;

    private TextView xiangnei_zhitiduan;
    private TextView xiangnei_jiaodu;
    private TextView xiangnei_pinglv;
    private TextView test_time;
    private TextView test_hand;

    private boolean isBound = false;
    private LinearLayout userform;
    private LinearLayout reportform;
    private Button confirmBtn;
    private Button cancelBtn;
    private EditText etName;
    private EditText etAge;
    private RadioGroup rgGender;
    private Integer handDir;
    private Boolean isSaveUserFile=true;
    private DataProcessorManagerRight processorManagerRight;
    private Integer conDeviceNum=1;
    private String deviceMacLeft;
    private String deviceMacRight;
    private Boolean isJiaozhun1=false;
    private Boolean isJiaozhun2=false;
    private LinearLayout groupSpinner;
    private Spinner spinner;
    private Integer selectedSensorNum=0;
//    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();
//    private ConcurrentLinkedQueue<byte[]> dataQueue2 = new ConcurrentLinkedQueue<>();
private LinkedBlockingDeque<byte[]> dataQueue = new LinkedBlockingDeque<>();
    private LinkedBlockingDeque<byte[]> dataQueue2 = new LinkedBlockingDeque<>();
    private LinearLayout group_button;
    private Button leftButton;
    private Button rightButton;
    private Integer isSelectButton=1;
    private FrameLayout loadingLayout;

    private String userName="";
    private String userAge="";
    private String userGender="";
    private Boolean isSaveUserFileDone=false;
    private Boolean isFileMiss=false;

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            if(conDeviceNum==1){
                if(handDir==1) {
                    dataQueue  = bluetoothService.getDataQueueLeft();
                    processorManager = DataProcessorManager.getInstance(dataQueue);
                }else{
                    dataQueue2  = bluetoothService.getDataQueueRight();
                    processorManager = DataProcessorManager.getInstance(dataQueue2);
                }
                processorManager.setDataUpdateListener(TestResActivity.this);
                processorManager.startProcessing();
                processorManager.setDeviceMac(deviceId.replace(":", ""));
                processorManager.temp = handDir;
                processorManager.setProcessingFunction(ProcessingFunction.FinalRes);
            }
            else{
                dataQueue  = bluetoothService.getDataQueueLeft();
                dataQueue2  = bluetoothService.getDataQueueRight();
                processorManager = DataProcessorManager.getInstance(dataQueue);
                processorManager.setDataUpdateListener(TestResActivity.this);
                processorManager.startProcessing();
                processorManager.setDeviceMac(deviceMacLeft.replace(":",""));
                processorManager.temp = 1;
                processorManager.setProcessingFunction(ProcessingFunction.FinalRes);

                processorManagerRight=DataProcessorManagerRight.getInstance(dataQueue2);
                processorManagerRight.setDataUpdateListener(TestResActivity.this);
                processorManagerRight.startProcessing();
                processorManagerRight.setDeviceMac(deviceMacRight.replace(":",""));
                processorManagerRight.temp = 2;
                processorManagerRight.setProcessingFunction(ProcessingFunction.FinalRes);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CrashHandler.getInstance().init(this);
        setContentView(R.layout.activity_test_res);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("测试结果报告");
        loadingLayout  = findViewById(R.id.loadingLayout);

        group_button=findViewById(R.id.group_button);
        leftButton=findViewById(R.id.leftButton);
        rightButton=findViewById(R.id.rightButton);
        test_hand=findViewById(R.id.test_hand);
        test_time=findViewById(R.id.test_time);
        test_time.setText("测试时间:"+getCurrentTime());
        group_button.setVisibility(View.GONE);

        duizhi_jiaosudu=findViewById(R.id.duizhi_jiaosudu);
        dakai_jiaosudu=findViewById(R.id.dakai_jiaosudu);
        bihe_jiaosudu=findViewById(R.id.bihe_jiaosudu);
        duizhi_cishu=findViewById(R.id.duizhi_cishu);
        yuce_label=findViewById(R.id.yuce_label);
        yuce_score=findViewById(R.id.yuce_score);

        zhenchan_lable=findViewById(R.id.zhenchan_lable);
        zhenchan_score=findViewById(R.id.zhenchan_score);
        pingju_score=findViewById(R.id.pingju_score);
        xiangxia_score=findViewById(R.id.xiangxia_score);
        xiangnei_score=findViewById(R.id.xiangnei_score);

        jingzhi_jizhiduan=findViewById(R.id.jingzhi_jizhiduan);
        jingzhi_jiaodu=findViewById(R.id.jingzhi_jiaodu);
        jingzhi_pinglv=findViewById(R.id.jingzhi_pinglv);

        pingju_zhitiduan=findViewById(R.id.pingju_zhitiduan);
        pingju_jiaodu=findViewById(R.id.pingju_jiaodu);
        pingju_pinglv=findViewById(R.id.pingju_pinglv);

        xiangxia_zhitiduan=findViewById(R.id.xiangxia_zhitiduan);
        xiangxia_jiaodu=findViewById(R.id.xiangxia_jiaodu);
        xiangxia_pinglv=findViewById(R.id.xiangxia_pinglv);

        xiangnei_zhitiduan=findViewById(R.id.xiangnei_zhitiduan);
        xiangnei_jiaodu=findViewById(R.id.xiangnei_jiaodu);
        xiangnei_pinglv=findViewById(R.id.xiangnei_pinglv);

        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        conDeviceNum = sp.getInt("conDeviceNum", 1);
        if(conDeviceNum==1) {
            handDir = sp.getInt("handDirection",0);
            if(handDir==1){
                deviceId = sp.getString("DEVICE_ADDRESS_LEFT", "");
                test_hand.setText("测试手:左手");
            }else{
                deviceId = sp.getString("DEVICE_ADDRESS_RIGHT", "");
                test_hand.setText("测试手:右手");
            }
            predictLabel = sp.getInt("predictLabel", 0);
            predictScore = sp.getInt("predictScore", 0);
            String saved = sp.getString("displayFea", "");
            System.out.println("testres----:"+saved);
            if (!saved.isEmpty()) {
                String[] parts = saved.split(",");
                if (parts.length == 4) {
                    duizhi_jiaosudu_str = String.format(Locale.US, "%.2e", Double.valueOf(parts[0])).toString();
                    duizhi_jiaosudu.setText( duizhi_jiaosudu_str+ "rad/s");
                    dakai_jiaosudu_str = String.format(Locale.US, "%.2e", Double.valueOf(parts[1])).toString();
                    dakai_jiaosudu.setText(dakai_jiaosudu_str+ "rad/s");
                    bihe_jiaosudu_str=String.format(Locale.US, "%.2e", Double.valueOf(parts[2])).toString();
                    bihe_jiaosudu.setText(bihe_jiaosudu_str + "rad/s");
                    duizhi_cishu_str=parts[3];
                    duizhi_cishu.setText(duizhi_cishu_str + "次");
                    yuce_label_str = predictLabel.toString();
                    yuce_label.setText(predictLabel.toString());
                    yuce_score_str=predictScore.toString();
                    yuce_score.setText(predictScore.toString());
                } else {
                    Toast.makeText(TestResActivity.this, "结果有错误，请重试", Toast.LENGTH_SHORT).show();
                }
            }

        }
        if(conDeviceNum==2){
            leftButton.setBackgroundColor(getResources().getColor(R.color.btnColor));
            rightButton.setBackgroundColor(getResources().getColor(com.androidplot.R.color.ap_gray));
            deviceMacLeft = sp.getString("DEVICE_ADDRESS_LEFT","");
            deviceMacRight=sp.getString("DEVICE_ADDRESS_RIGHT","");
                predictLabel = sp.getInt("predictLabel", 0);
                predictScore = sp.getInt("predictScore", 0);
                String saved = sp.getString("displayFea", "");
                System.out.println("testres----:"+saved);
                if (!saved.isEmpty()) {
                    String[] parts = saved.split(",");
                    if (parts.length == 4) {
                        duizhi_jiaosudu_str = String.format(Locale.US, "%.2e", Double.valueOf(parts[0])).toString();
                       // duizhi_jiaosudu.setText( duizhi_jiaosudu_str+ "rad/s");
                        dakai_jiaosudu_str = String.format(Locale.US, "%.2e", Double.valueOf(parts[1])).toString();
                       // dakai_jiaosudu.setText(dakai_jiaosudu_str+ "rad/s");
                        bihe_jiaosudu_str=String.format(Locale.US, "%.2e", Double.valueOf(parts[2])).toString();
                       // bihe_jiaosudu.setText(bihe_jiaosudu_str + "rad/s");
                        duizhi_cishu_str=parts[3];
                      //  duizhi_cishu.setText(duizhi_cishu_str + "次");
                        yuce_label_str = predictLabel.toString();
                      //  yuce_label.setText(predictLabel.toString());
                        yuce_score_str=predictScore.toString();
                      //  yuce_score.setText(predictScore.toString());
                    } else {
                        Toast.makeText(TestResActivity.this, "结果有错误，请重试", Toast.LENGTH_SHORT).show();
                    }
                }
            predictLabelR = sp.getInt("predictLabelR", 0);
            predictScoreR = sp.getInt("predictScoreR", 0);
            String savedR = sp.getString("displayFeaR", "");
            if (!savedR.isEmpty()) {
                String[] partsR = savedR.split(",");
                if (partsR.length == 4) {
                    duizhi_jiaosudu_strR = String.format(Locale.US, "%.2e", Double.valueOf(partsR[0])).toString();
                    dakai_jiaosudu_strR = String.format(Locale.US, "%.2e", Double.valueOf(partsR[1])).toString();
                    bihe_jiaosudu_strR =String.format(Locale.US, "%.2e", Double.valueOf(partsR[2])).toString();
                    duizhi_cishu_strR =partsR[3];
                    yuce_label_strR = predictLabelR.toString();
                    yuce_score_strR =predictScoreR.toString();
                } else {
                    Toast.makeText(TestResActivity.this, "结果有错误，请重试", Toast.LENGTH_SHORT).show();
                }
            }

        }

        userform=findViewById(R.id.user_form);
        confirmBtn =findViewById(R.id.btn_confirm);
        cancelBtn = findViewById(R.id.btn_cancel);
        etName = findViewById(R.id.et_name);
        etAge = findViewById(R.id.et_age);
        rgGender = findViewById(R.id.rg_gender);
        reportform=findViewById(R.id.report_form);
        reportform.setVisibility(View.GONE);
        confirmBtn.setOnClickListener(v -> {
            if (isFileMiss == false) {

                userName = etName.getText().toString().trim();
                userAge = etAge.getText().toString().trim();
                int checkedId = rgGender.getCheckedRadioButtonId();
                if (checkedId == R.id.rb_male) {
                    userGender = "男";
                }
                if (checkedId == R.id.rb_female) {
                    userGender = "女";
                }
                // 在这里处理用户输入
                //Toast.makeText(this, "姓名:" + name + " 性别:" + gender + " 年龄:" + age, Toast.LENGTH_SHORT).show();
                if (userName.isEmpty()) {
                    Toast.makeText(this, "姓名不能为空", Toast.LENGTH_SHORT).show();
                } else if (userGender.isEmpty()) {
                    Toast.makeText(this, "性别不能为空", Toast.LENGTH_SHORT).show();

                } else if (userAge.isEmpty()) {
                    Toast.makeText(this, "年龄不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    loadingLayout.setVisibility(View.VISIBLE);
                    userform.setVisibility(View.GONE);
                    reportform.setVisibility(View.VISIBLE);
                }
                if (conDeviceNum == 2) {
                    group_button.setVisibility(View.VISIBLE);
                }
            }else{
                Toast.makeText(this,"缺少文件，是否有测试未完成",Toast.LENGTH_SHORT).show();
            }

        });
        cancelBtn.setOnClickListener(v -> {
            if(isFileMiss==false) {
                loadingLayout.setVisibility(View.VISIBLE);
                userform.setVisibility(View.GONE);
                reportform.setVisibility(View.VISIBLE);
                if (conDeviceNum == 2) {
                    group_button.setVisibility(View.VISIBLE);
                }
            }else{
                Toast.makeText(this,"缺少文件，是否有测试未完成",Toast.LENGTH_SHORT).show();

            }

        });
        leftButton.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  leftButton.setBackgroundColor(getResources().getColor(R.color.btnColor));
                  rightButton.setBackgroundColor(getResources().getColor(com.androidplot.R.color.ap_gray));
                  duizhi_jiaosudu.setText( duizhi_jiaosudu_str+ "rad/s");
                  dakai_jiaosudu.setText(dakai_jiaosudu_str+ "rad/s");
                  bihe_jiaosudu.setText(bihe_jiaosudu_str + "rad/s");
                  duizhi_cishu.setText(duizhi_cishu_str + "次");
                  yuce_label.setText(utils.duizhiLabelChange(predictLabel));
                  yuce_score.setText(predictScore.toString());
                  zhenchan_lable.setText(utils.zhenchanLabelChange(pred1ctLabe1));
                  zhenchan_score.setText(String.valueOf(RTScore));
                  pingju_score.setText(String.valueOf(PScore));
                  xiangxia_score.setText(String.valueOf(PTScore));
                  xiangnei_score.setText(String.valueOf(PTTScoreRTDisFea));

                  jingzhi_jizhiduan.setText(utils.resChange((int)RTDisFea[0]));
                  jingzhi_jiaodu.setText(String.valueOf(RTDisFea[1])+" deg");
                  jingzhi_pinglv.setText(String.valueOf(RTDisFea[2])+" HZ");

                  pingju_zhitiduan.setText(utils.resChange((int)PDisFea[0]));
                  pingju_jiaodu.setText(String.valueOf(PDisFea[1])+" deg");
                  pingju_pinglv.setText(String.valueOf(PDisFea[2])+" HZ");

                  xiangxia_zhitiduan.setText(utils.resChange((int)PTDisFea[0]));
                  xiangxia_jiaodu.setText(String.valueOf(PTDisFea[1])+" deg");
                  xiangxia_pinglv.setText(String.valueOf(PTDisFea[2])+" HZ");

                  xiangnei_zhitiduan.setText(utils.resChange((int)PTTDisFea[0]));
                  xiangnei_jiaodu.setText(String.valueOf(PTTDisFea[1])+" deg");
                  xiangnei_pinglv.setText(String.valueOf(PTTDisFea[2])+" HZ");
              }
        });
        rightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leftButton.setBackgroundColor(getResources().getColor(com.androidplot.R.color.ap_gray));
                rightButton.setBackgroundColor(getResources().getColor(R.color.btnColor));
                duizhi_jiaosudu.setText( duizhi_jiaosudu_strR+ "rad/s");
                dakai_jiaosudu.setText(dakai_jiaosudu_strR+ "rad/s");
                bihe_jiaosudu.setText(bihe_jiaosudu_strR + "rad/s");
                duizhi_cishu.setText(duizhi_cishu_strR + "次");
                yuce_label.setText(utils.duizhiLabelChange(predictLabelR));
                yuce_score.setText(predictScoreR.toString());

                zhenchan_lable.setText(utils.zhenchanLabelChange(pred1ctLabe1R));
                zhenchan_score.setText(String.valueOf(RTScoreR));
                pingju_score.setText(String.valueOf(PScoreR));
                xiangxia_score.setText(String.valueOf(PTScoreR));
                xiangnei_score.setText(String.valueOf(PTTScoreRTDisFeaR));

                jingzhi_jizhiduan.setText(utils.resChange((int)RTDisFeaR[0]));
                jingzhi_jiaodu.setText(String.valueOf(RTDisFeaR[1])+" deg");
                jingzhi_pinglv.setText(String.valueOf(RTDisFeaR[2])+" HZ");

                pingju_zhitiduan.setText(utils.resChange((int)PDisFeaR[0]));
                pingju_jiaodu.setText(String.valueOf(PDisFeaR[1])+" deg");
                pingju_pinglv.setText(String.valueOf(PDisFeaR[2])+" HZ");

                xiangxia_zhitiduan.setText(utils.resChange((int)PTDisFeaR[0]));
                xiangxia_jiaodu.setText(String.valueOf(PTDisFeaR[1])+" deg");
                xiangxia_pinglv.setText(String.valueOf(PTDisFeaR[2])+" HZ");

                xiangnei_zhitiduan.setText(utils.resChange((int)PTTDisFeaR[0]));
                xiangnei_jiaodu.setText(String.valueOf(PTTDisFeaR[1])+" deg");
                xiangnei_pinglv.setText(String.valueOf(PTTDisFeaR[2])+" HZ");
            }
        });

    }
    public static String getCurrentTime() {
        // 获取当前时间
        Date now = new Date();
        // 定义时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        // 格式化并返回
        return sdf.format(now);
    }
    public void saveUserFormFile(String name,String age,String sex){
        try {
            if(conDeviceNum==1) {
                JSONObject obj = new JSONObject();
                obj.put("姓名", name);
                obj.put("性别", sex);
                obj.put("年龄", age);
                JSONObject duizhi_obj = new JSONObject();
                if (!duizhi_jiaosudu_str.isEmpty() && !dakai_jiaosudu_str.isEmpty() && !bihe_jiaosudu_str.isEmpty() && !duizhi_cishu_str.isEmpty() && predictLabel != null && predictScore != null) {
                    duizhi_obj.put("对指角速度均方根", duizhi_jiaosudu_str);
                    duizhi_obj.put("打开角速度均方根", dakai_jiaosudu_str);
                    duizhi_obj.put("闭合角速度均方根", bihe_jiaosudu_str);
                    duizhi_obj.put("完成对指次数", duizhi_cishu_str);
                    duizhi_obj.put("预测的标签", utils.duizhiLabelChange(predictLabel));
                    duizhi_obj.put("预测评分", predictScore);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject zhenchanobj = new JSONObject();
                if (pred1ctLabe1 != null && RTScore != null && PScore != null && PTScore != null && PTTScoreRTDisFea != null) {
                    zhenchanobj.put("疾病分类标签", utils.zhenchanLabelChange(pred1ctLabe1));
                    zhenchanobj.put("静止性震颤评分", RTScore);
                    zhenchanobj.put("姿势性震颤平举评分", PScore);
                    zhenchanobj.put("双手置于胸前手心向下评分", PTScore);
                    zhenchanobj.put("双手置于胸前手心向内评分", PTTScoreRTDisFea);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject jingzhi_pbj = new JSONObject();
                if (RTDisFea != null && RTDisFea.length == 3) {
                    jingzhi_pbj.put("最大震颤肢体段", utils.resChange((int) RTDisFea[0]));
                    jingzhi_pbj.put("最大震颤角度", RTDisFea[1]);
                    jingzhi_pbj.put("平均震颤频率", RTDisFea[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject pingju_pbj = new JSONObject();
                if (PDisFea != null && PDisFea.length == 3) {
                    pingju_pbj.put("最大震颤肢体段", utils.resChange((int) PDisFea[0]));
                    pingju_pbj.put("最大震颤角度", PDisFea[1]);
                    pingju_pbj.put("平均震颤频率", PDisFea[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject xiangxia_pbj = new JSONObject();
                if (PTDisFea != null && PTDisFea.length == 3) {
                    xiangxia_pbj.put("最大震颤肢体段", utils.resChange((int) PTDisFea[0]));
                    xiangxia_pbj.put("最大震颤角度", PTDisFea[1]);
                    xiangxia_pbj.put("平均震颤频率", PTDisFea[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject xiangnei_pbj = new JSONObject();
                if (PTTDisFea != null && PTTDisFea.length == 3) {
                    xiangnei_pbj.put("最大震颤肢体段", utils.resChange((int) PTTDisFea[0]));
                    xiangnei_pbj.put("最大震颤角度", PTTDisFea[1]);
                    xiangnei_pbj.put("平均震颤频率", PTTDisFea[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }

                JSONObject ceshi_obj = new JSONObject();
                ceshi_obj.put("对指测试指标", duizhi_obj);
                ceshi_obj.put("震颤测试指标", zhenchanobj);
                ceshi_obj.put("静止性震颤测试指标", jingzhi_pbj);
                ceshi_obj.put("平举测试指标", pingju_pbj);
                ceshi_obj.put("双手置于胸前手心向下测试指标", xiangxia_pbj);
                ceshi_obj.put("双手置于胸前手心向内测试指标", xiangnei_pbj);

                JSONObject res_obj = new JSONObject();
                res_obj.put("用户信息", obj);
                if(handDir==1){
                    res_obj.put("左手", ceshi_obj);
                }else{
                    res_obj.put("右手", ceshi_obj);
                }

                String jsonStr = res_obj.toString();
                if (isSaveUserFile == true) {
                    utils.writeToFile(jsonStr, "user_info.txt");
                }
            }else{
                JSONObject obj = new JSONObject();
                obj.put("姓名", name);
                obj.put("性别", sex);
                obj.put("年龄", age);
                JSONObject duizhi_obj = new JSONObject();
                //left hand
                if (!duizhi_jiaosudu_str.isEmpty() && !dakai_jiaosudu_str.isEmpty() && !bihe_jiaosudu_str.isEmpty() && !duizhi_cishu_str.isEmpty() && predictLabel != null && predictScore != null) {
                    duizhi_obj.put("对指角速度均方根", duizhi_jiaosudu_str);
                    duizhi_obj.put("打开角速度均方根", dakai_jiaosudu_str);
                    duizhi_obj.put("闭合角速度均方根", bihe_jiaosudu_str);
                    duizhi_obj.put("完成对指次数", duizhi_cishu_str);
                    duizhi_obj.put("预测的标签", utils.duizhiLabelChange(predictLabel));
                    duizhi_obj.put("预测评分", predictScore);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject zhenchanobj = new JSONObject();
                if (pred1ctLabe1 != null && RTScore != null && PScore != null && PTScore != null && PTTScoreRTDisFea != null) {
                    zhenchanobj.put("疾病分类标签", utils.zhenchanLabelChange(pred1ctLabe1));
                    zhenchanobj.put("静止性震颤评分", RTScore);
                    zhenchanobj.put("姿势性震颤平举评分", PScore);
                    zhenchanobj.put("双手置于胸前手心向下评分", PTScore);
                    zhenchanobj.put("双手置于胸前手心向内评分", PTTScoreRTDisFea);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject jingzhi_pbj = new JSONObject();
                if (RTDisFea != null && RTDisFea.length == 3) {
                    jingzhi_pbj.put("最大震颤肢体段", utils.resChange((int) RTDisFea[0]));
                    jingzhi_pbj.put("最大震颤角度", RTDisFea[1]);
                    jingzhi_pbj.put("平均震颤频率", RTDisFea[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject pingju_pbj = new JSONObject();
                if (PDisFea != null && PDisFea.length == 3) {
                    pingju_pbj.put("最大震颤肢体段", utils.resChange((int) PDisFea[0]));
                    pingju_pbj.put("最大震颤角度", PDisFea[1]);
                    pingju_pbj.put("平均震颤频率", PDisFea[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject xiangxia_pbj = new JSONObject();
                if (PTDisFea != null && PTDisFea.length == 3) {
                    xiangxia_pbj.put("最大震颤肢体段", utils.resChange((int) PTDisFea[0]));
                    xiangxia_pbj.put("最大震颤角度", PTDisFea[1]);
                    xiangxia_pbj.put("平均震颤频率", PTDisFea[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject xiangnei_pbj = new JSONObject();
                if (PTTDisFea != null && PTTDisFea.length == 3) {
                    xiangnei_pbj.put("最大震颤肢体段", utils.resChange((int) PTTDisFea[0]));
                    xiangnei_pbj.put("最大震颤角度", PTTDisFea[1]);
                    xiangnei_pbj.put("平均震颤频率", PTTDisFea[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }

                JSONObject ceshi_obj = new JSONObject();
                ceshi_obj.put("对指测试指标", duizhi_obj);
                ceshi_obj.put("震颤测试指标", zhenchanobj);
                ceshi_obj.put("静止性震颤测试指标", jingzhi_pbj);
                ceshi_obj.put("平举测试指标", pingju_pbj);
                ceshi_obj.put("双手置于胸前手心向下测试指标", xiangxia_pbj);
                ceshi_obj.put("双手置于胸前手心向内测试指标", xiangnei_pbj);
                //right hand
                JSONObject duizhi_obj_rit = new JSONObject();
                if (!duizhi_jiaosudu_strR.isEmpty() && !dakai_jiaosudu_strR.isEmpty() && !bihe_jiaosudu_strR.isEmpty() && !duizhi_cishu_strR.isEmpty() && predictLabelR != null && predictScoreR != null) {
                    duizhi_obj_rit.put("对指角速度均方根", duizhi_jiaosudu_strR);
                    duizhi_obj_rit.put("打开角速度均方根", dakai_jiaosudu_strR);
                    duizhi_obj_rit.put("闭合角速度均方根", bihe_jiaosudu_strR);
                    duizhi_obj_rit.put("完成对指次数", duizhi_cishu_strR);
                    duizhi_obj_rit.put("预测的标签", utils.duizhiLabelChange(predictLabelR));
                    duizhi_obj_rit.put("预测评分", predictScoreR);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject zhenchanobj_rit = new JSONObject();
                if (pred1ctLabe1R != null && RTScoreR != null && PScoreR != null && PTScoreR != null && PTTScoreRTDisFeaR != null) {
                    zhenchanobj_rit.put("疾病分类标签", utils.zhenchanLabelChange(pred1ctLabe1R));
                    zhenchanobj_rit.put("静止性震颤评分", RTScoreR);
                    zhenchanobj_rit.put("姿势性震颤平举评分", PScoreR);
                    zhenchanobj_rit.put("双手置于胸前手心向下评分", PTScoreR);
                    zhenchanobj_rit.put("双手置于胸前手心向内评分", PTTScoreRTDisFeaR);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject jingzhi_pbj_rit = new JSONObject();
                if (RTDisFeaR != null && RTDisFeaR.length == 3) {
                    jingzhi_pbj_rit.put("最大震颤肢体段", utils.resChange((int) RTDisFeaR[0]));
                    jingzhi_pbj_rit.put("最大震颤角度", RTDisFeaR[1]);
                    jingzhi_pbj_rit.put("平均震颤频率", RTDisFeaR[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject pingju_pbj_rit = new JSONObject();
                if (PDisFeaR != null && PDisFeaR.length == 3) {
                    pingju_pbj_rit.put("最大震颤肢体段", utils.resChange((int) PDisFeaR[0]));
                    pingju_pbj_rit.put("最大震颤角度", PDisFeaR[1]);
                    pingju_pbj_rit.put("平均震颤频率", PDisFeaR[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject xiangxia_pbj_rit = new JSONObject();
                if (PTDisFeaR != null && PTDisFeaR.length == 3) {
                    xiangxia_pbj_rit.put("最大震颤肢体段", utils.resChange((int) PTDisFeaR[0]));
                    xiangxia_pbj_rit.put("最大震颤角度", PTDisFeaR[1]);
                    xiangxia_pbj_rit.put("平均震颤频率", PTDisFeaR[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }
                JSONObject xiangnei_pbj_rit = new JSONObject();
                if (PTTDisFeaR != null && PTTDisFeaR.length == 3) {
                    xiangnei_pbj_rit.put("最大震颤肢体段", utils.resChange((int) PTTDisFeaR[0]));
                    xiangnei_pbj_rit.put("最大震颤角度", PTTDisFeaR[1]);
                    xiangnei_pbj_rit.put("平均震颤频率", PTTDisFeaR[2]);
                } else {
                    isSaveUserFile = false;
                    Toast.makeText(this, "数据不全", Toast.LENGTH_SHORT).show();
                }

                JSONObject ceshi_obj_rit = new JSONObject();
                ceshi_obj_rit.put("对指测试指标", duizhi_obj_rit);
                ceshi_obj_rit.put("震颤测试指标", zhenchanobj_rit);
                ceshi_obj_rit.put("静止性震颤测试指标", jingzhi_pbj_rit);
                ceshi_obj_rit.put("平举测试指标", pingju_pbj_rit);
                ceshi_obj_rit.put("双手置于胸前手心向下测试指标", xiangxia_pbj_rit);
                ceshi_obj_rit.put("双手置于胸前手心向内测试指标", xiangnei_pbj_rit);

                JSONObject res_obj = new JSONObject();
                res_obj.put("用户信息", obj);
                res_obj.put("左手", ceshi_obj);
                res_obj.put("右手", ceshi_obj_rit);
                String jsonStr = res_obj.toString();
                if (isSaveUserFile == true) {
                    utils.writeToFile(jsonStr, "user_info.txt");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if(name!=null && !name.isEmpty()) {
            System.out.println("changeFileNames-----------:yes--"+name);
            changeFileNames();
        }else{
            System.out.println("changeFileNames-----------:no---"+name);
            changeFileNamesNull();
        }
    }
    public void changeFileNames(){
        File dir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), "ParkinsonData");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if(conDeviceNum==1) {
            String hand="L";
            if(handDir==1){
                hand="L";
            }else{
                hand="R";
            }
            String did=deviceId.replace(":", "");
            File duizhiFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), did + "_" + handDir + "_H.txt");
            File duizhiFile_new = new File(dir, userName+"_"+did + "_"+hand+"_H_"+generateTimestamp()+".txt");
//                duizhiFile.renameTo(duizhiFile_new);
            copyFile(duizhiFile,duizhiFile_new);

            File RTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), did + "_RT_rawout.txt");
            File RTFile_new = new File(dir, userName+"_"+did + "_RT_rawout_"+hand+"_"+generateTimestamp()+".txt");
//            RTFile.renameTo(RTFile_new);
            copyFile(RTFile,RTFile_new);

            File PFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), did + "_P_rawout.txt");
            File PFile_new = new File(dir, userName+"_"+did + "_P_rawout_"+hand+"_"+generateTimestamp()+".txt");
//            PFile.renameTo(PFile_new);
            copyFile(PFile,PFile_new);

            File PTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), did + "_PT_rawout.txt");
            File PTFile_new = new File(dir, userName+"_"+did + "_PT_rawout_"+hand+"_"+generateTimestamp()+".txt");
//            PTFile.renameTo(PTFile_new);
            copyFile(PTFile,PTFile_new);

            File PTTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), did + "_PTT_rawout.txt");
            File PTTFile_new = new File(dir, userName+"_"+did + "_PTT_rawout_"+hand+"_"+generateTimestamp()+".txt");
//            PTTFile.renameTo(PTTFile_new);
            copyFile(PTTFile,PTTFile_new);

            File userFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), "user_info.txt");
            File userFile_new = new File(dir, userName+"_report_"+generateTimestamp()+".txt");
//            userFile.renameTo(userFile_new);
            copyFile(userFile,userFile_new);

        }else{
            String didl=deviceMacLeft.replace(":", "");
            String didr=deviceMacRight.replace(":", "");

            File duizhiFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didl + "_1_H.txt");
            File duizhiFile_new = new File(dir, userName+"_"+didl + "_L_H_"+generateTimestamp()+".txt");
//            duizhiFile.renameTo(duizhiFile_new);
            copyFile(duizhiFile,duizhiFile_new);

            File duizhiFileR = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didr + "_2_H.txt");
            File duizhiFileR_new = new File(dir, userName+"_"+didr + "_R_H_"+generateTimestamp()+".txt");
//            duizhiFileR.renameTo(duizhiFileR_new);
            copyFile(duizhiFileR,duizhiFileR_new);

            File RTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didl + "_RT_rawout.txt");
            File RTFile_new = new File(dir, userName+"_"+didl + "_RT_rawout_L_"+generateTimestamp()+".txt");
//            RTFile.renameTo(RTFile_new);
            copyFile(RTFile,RTFile_new);

            File RTFileR = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didr + "_RT_rawout.txt");
            File RTFileR_new = new File(dir, userName+"_"+didr + "_RT_rawout_R_"+generateTimestamp()+".txt");
//            RTFileR.renameTo(RTFileR_new);
            copyFile(RTFileR,RTFileR_new);

            File PFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didl + "_P_rawout.txt");
            File PFile_new = new File(dir, userName+"_"+didl + "_P_rawout_L_"+generateTimestamp()+".txt");
//            PFile.renameTo(PFile_new);
            copyFile(PFile,PFile_new);

            File PFileR = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didr + "_P_rawout.txt");
            File PFileR_new = new File(dir, userName+"_"+didr + "_P_rawout_R_"+generateTimestamp()+".txt");
//            PFileR.renameTo(PFileR_new);
            copyFile(PFileR,PFileR_new);

            File PTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didl + "_PT_rawout.txt");
            File PTFile_new = new File(dir, userName+"_"+didl + "_PT_rawout_L_"+generateTimestamp()+".txt");
//            PTFile.renameTo(PTFile_new);
            copyFile(PTFile,PTFile_new);

            File PTFileR = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didr + "_PT_rawout.txt");
            File PTFileR_new = new File(dir, userName+"_"+didr + "_PT_rawout_R_"+generateTimestamp()+".txt");
//            PTFileR.renameTo(PTFileR_new);
            copyFile(PTFileR,PTFileR_new);

            File PTTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didl + "_PTT_rawout.txt");
            File PTTFile_new = new File(dir, userName+"_"+didl + "_PTT_rawout_L_"+generateTimestamp()+".txt");
//            PTTFile.renameTo(PTTFile_new);
            copyFile(PTTFile,PTTFile_new);

            File PTTFileR = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didr + "_PTT_rawout.txt");
            File PTTFileR_new = new File(dir, userName+"_"+didr + "_PTT_rawout_R_"+generateTimestamp()+".txt");
//            PTTFileR.renameTo(PTTFileR_new);
            copyFile(PTTFileR,PTTFileR_new);

            File userFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), "user_info.txt");
            File userFile_new = new File(dir, userName+"_report_"+generateTimestamp()+".txt");
//            userFile.renameTo(userFile_new);
            copyFile(userFile,userFile_new);
        }
    }
    public void changeFileNamesNull(){
        File dir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), "ParkinsonData");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        if(conDeviceNum==1) {
            String hand="L";
            if(handDir==1){
                hand="L";
            }else{
                hand="R";
            }
            String did=deviceId.replace(":", "");
            File duizhiFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), did + "_" + handDir + "_H.txt");
            File duizhiFile_new = new File(dir, did + "_"+hand+"_H_"+generateTimestamp()+".txt");
//            duizhiFile.renameTo(duizhiFile_new);
           Boolean dd= copyFile(duizhiFile,duizhiFile_new);
            System.out.println("changeFileNames--------isdone:"+dd);
            File RTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), did + "_RT_rawout.txt");
            File RTFile_new = new File(dir, did + "_RT_rawout_"+hand+"_"+generateTimestamp()+".txt");
//            RTFile.renameTo(RTFile_new);
            copyFile(RTFile,RTFile_new);

            File PFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), did + "_P_rawout.txt");
            File PFile_new = new File(dir, did + "_P_rawout_"+hand+"_"+generateTimestamp()+".txt");
//            PFile.renameTo(PFile_new);
            copyFile(PFile,PFile_new);

            File PTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), did + "_PT_rawout.txt");
            File PTFile_new = new File(dir, did + "_PT_rawout_"+hand+"_"+generateTimestamp()+".txt");
//            PTFile.renameTo(PTFile_new);
            copyFile(PTFile,PTFile_new);

            File PTTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), did + "_PTT_rawout.txt");
            File PTTFile_new = new File(dir, did + "_PTT_rawout_"+hand+"_"+generateTimestamp()+".txt");
//            PTTFile.renameTo(PTTFile_new);
            copyFile(PTTFile,PTTFile_new);

            File userFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), "user_info.txt");
            File userFile_new = new File(dir, did+"_report_"+generateTimestamp()+".txt");
//            userFile.renameTo(userFile_new);
            copyFile(userFile,userFile_new);

        }else{
            String didl=deviceMacLeft.replace(":", "");
            String didr=deviceMacRight.replace(":", "");
            File duizhiFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didl + "_1_H.txt");
            File duizhiFile_new = new File(dir, didl + "_L_H_"+generateTimestamp()+".txt");
//            duizhiFile.renameTo(duizhiFile_new);
            copyFile(duizhiFile,duizhiFile_new);

            File duizhiFileR = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didr + "_2_H.txt");
            File duizhiFileR_new = new File(dir, didr + "_R_H_"+generateTimestamp()+".txt");
//            duizhiFileR.renameTo(duizhiFileR_new);
            copyFile(duizhiFileR,duizhiFileR_new);

            File RTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didl + "_RT_rawout.txt");
            File RTFile_new = new File(dir, didl + "_RT_rawout_L_"+generateTimestamp()+".txt");
//            RTFile.renameTo(RTFile_new);
            copyFile(RTFile,RTFile_new);

            File RTFileR = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didr + "_RT_rawout.txt");
            File RTFileR_new = new File(dir, didr + "_RT_rawout_R_"+generateTimestamp()+".txt");
//            RTFileR.renameTo(RTFileR_new);
            copyFile(RTFileR,RTFileR_new);

            File PFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didl + "_P_rawout.txt");
            File PFile_new = new File(dir, didl + "_P_rawout_L_"+generateTimestamp()+".txt");
//            PFile.renameTo(PFile_new);
            copyFile(PFile,PFile_new);

            File PFileR = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didr + "_P_rawout.txt");
            File PFileR_new = new File(dir, didr + "_P_rawout_R_"+generateTimestamp()+".txt");
//            PFileR.renameTo(PFileR_new);
            copyFile(PFileR,PFileR_new);

            File PTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didl + "_PT_rawout.txt");
            File PTFile_new = new File(dir, didl + "_PT_rawout_L_"+generateTimestamp()+".txt");
//            PTFile.renameTo(PTFile_new);
            copyFile(PTFile,PTFile_new);

            File PTFileR = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didr + "_PT_rawout.txt");
            File PTFileR_new = new File(dir, didr + "_PT_rawout_R_"+generateTimestamp()+".txt");
//            PTFileR.renameTo(PTFileR_new);
            copyFile(PTFileR,PTFileR_new);

            File PTTFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didl + "_PTT_rawout.txt");
            File PTTFile_new = new File(dir, didl + "_PTT_rawout_L_"+generateTimestamp()+".txt");
//            PTTFile.renameTo(PTTFile_new);
            copyFile(PTTFile,PTTFile_new);

            File PTTFileR = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), didr + "_PTT_rawout.txt");
            File PTTFileR_new = new File(dir, didr + "_PTT_rawout_R_"+generateTimestamp()+".txt");
//            PTTFileR.renameTo(PTTFileR_new);
            copyFile(PTTFileR,PTTFileR_new);

            File userFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), "user_info.txt");
            File userFile_new = new File(dir, didl+"_"+didr+"_report_"+generateTimestamp()+".txt");
//            userFile.renameTo(userFile_new);
            copyFile(userFile,userFile_new);
        }
    }
    public String generateTimestamp() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        return sdf.format(new Date());
    }
    public static boolean copyFile(File src, File dst) {
        if (!src.exists()) return false;

        // 如果目标文件夹不存在，创建文件夹
        File parent = dst.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }

        try (InputStream in = new FileInputStream(src);
             OutputStream out = new FileOutputStream(dst)) {

            byte[] buffer = new byte[4096];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }

            out.flush();
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
        if(conDeviceNum==1) {
            if(handDir==1) {
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_LEFT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }else{
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }
        }
        if(conDeviceNum==2) {
            Intent intent = new Intent(this, BluetoothService.class);
            intent.putExtra("DEVICE_ADDRESS_LEFT", deviceMacLeft);
            intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceMacRight); // 如果需要
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }

    }
    @Override
    public void onDataProcessed(ProcessedData data) {
        String flag = data.getFlag();
        System.out.println("testRes-Flag:" + flag);
        if(flag.equals("fileNull")){
            Toast.makeText(this,"缺少文件，是否有测试未完成",Toast.LENGTH_SHORT).show();
            isFileMiss=true;
            return;
        }
        if(flag.equals("p_file_error")){
            Toast.makeText(this,"平举测试不合格，请重新测试",Toast.LENGTH_SHORT).show();
            isFileMiss=true;
            return;
        }
        if(flag.equals("rt_file_error")){
            Toast.makeText(this,"静止性震颤测试不合格，请重新测试",Toast.LENGTH_SHORT).show();
            isFileMiss=true;
            return;
        }
        if(flag.equals("pt_file_error")){
            Toast.makeText(this,"手心向下测试不合格，请重新测试",Toast.LENGTH_SHORT).show();
            isFileMiss=true;
            return;
        }
        if(flag.equals("ptt_file_error")){
            Toast.makeText(this,"手心向内测试不合格，请重新测试",Toast.LENGTH_SHORT).show();
            isFileMiss=true;
            return;
        }
        if (flag.equals("zhenchanResult")) {
            isJiaozhun1=true;
            ZhenChanResult zhenchanRes = data.getZhenChanResult();
            pred1ctLabe1=zhenchanRes.predictLabel;
            RTScore = zhenchanRes.RTScore;
            PScore =zhenchanRes.PScore;
            PTScore=zhenchanRes.PTScore;
            PTTScoreRTDisFea = zhenchanRes.PTTScore;
            RTDisFea = zhenchanRes.RTDisFea;
            PDisFea=zhenchanRes.PDisFea;
            PTDisFea = zhenchanRes.PTDisFea;
            PTTDisFea = zhenchanRes.PTTDisFea;
            System.out.println("testRes-isJiaozhun1:" + isJiaozhun1);
            System.out.println("testRes-isJiaozhun2:" + isJiaozhun2);

                duizhi_jiaosudu.setText( duizhi_jiaosudu_str+ "rad/s");
                dakai_jiaosudu.setText(dakai_jiaosudu_str+ "rad/s");
                bihe_jiaosudu.setText(bihe_jiaosudu_str + "rad/s");
                duizhi_cishu.setText(duizhi_cishu_str + "次");
                yuce_label.setText(utils.duizhiLabelChange(predictLabel));
                yuce_score.setText(predictScore.toString());
                zhenchan_lable.setText(utils.zhenchanLabelChange(pred1ctLabe1));
                zhenchan_score.setText(String.valueOf(RTScore));
                pingju_score.setText(String.valueOf(PScore));
                xiangxia_score.setText(String.valueOf(PTScore));
                xiangnei_score.setText(String.valueOf(PTTScoreRTDisFea));

                jingzhi_jizhiduan.setText(utils.resChange((int)RTDisFea[0]));
                jingzhi_jiaodu.setText(String.valueOf(RTDisFea[1])+" deg");
                jingzhi_pinglv.setText(String.valueOf(RTDisFea[2])+" HZ");

                pingju_zhitiduan.setText(utils.resChange((int)PDisFea[0]));
                pingju_jiaodu.setText(String.valueOf(PDisFea[1])+" deg");
                pingju_pinglv.setText(String.valueOf(PDisFea[2])+" HZ");

                xiangxia_zhitiduan.setText(utils.resChange((int)PTDisFea[0]));
                xiangxia_jiaodu.setText(String.valueOf(PTDisFea[1])+" deg");
                xiangxia_pinglv.setText(String.valueOf(PTDisFea[2])+" HZ");

                xiangnei_zhitiduan.setText(utils.resChange((int)PTTDisFea[0]));
                xiangnei_jiaodu.setText(String.valueOf(PTTDisFea[1])+" deg");
                xiangnei_pinglv.setText(String.valueOf(PTTDisFea[2])+" HZ");

        }
        if(conDeviceNum==1){
            if(isJiaozhun1==true){
                loadingLayout.setVisibility(View.GONE);
                if(isSaveUserFileDone==false){
                    saveUserFormFile(userName,userAge,userGender);
                    isSaveUserFileDone=true;
                }

            }
        }else{
            if(isJiaozhun1==true && isJiaozhun2==true){
                loadingLayout.setVisibility(View.GONE);
                if(isSaveUserFileDone==false){
                    saveUserFormFile(userName,userAge,userGender);
                    isSaveUserFileDone=true;
                }
            }
        }
    }
    @Override
    public void onDataProcessedRight(ProcessedData data) {
        String flag = data.getFlag();
        System.out.println("testRes-Flag:" + flag);
        if(flag.equals("fileNull")){
            Toast.makeText(this,"缺少文件，是否有测试未完成",Toast.LENGTH_SHORT).show();
            isFileMiss=true;
            return;
        }
        if (flag.equals("zhenchanResult")) {
            isJiaozhun2=true;
            ZhenChanResult zhenchanRes = data.getZhenChanResult();
            pred1ctLabe1R=zhenchanRes.predictLabel;
            RTScoreR = zhenchanRes.RTScore;
            PScoreR =zhenchanRes.PScore;
            PTScoreR=zhenchanRes.PTScore;
            PTTScoreRTDisFeaR = zhenchanRes.PTTScore;
            RTDisFeaR = zhenchanRes.RTDisFea;
            PDisFeaR=zhenchanRes.PDisFea;
            PTDisFeaR = zhenchanRes.PTDisFea;
            PTTDisFeaR = zhenchanRes.PTTDisFea;
            System.out.println("testRes-isJiaozhun1:" + isJiaozhun1);
            System.out.println("testRes-isJiaozhun2:" + isJiaozhun2);
            if(isJiaozhun1==true) {
                duizhi_jiaosudu.setText(duizhi_jiaosudu_str + "rad/s");
                dakai_jiaosudu.setText(dakai_jiaosudu_str + "rad/s");
                bihe_jiaosudu.setText(bihe_jiaosudu_str + "rad/s");
                duizhi_cishu.setText(duizhi_cishu_str + "次");
                yuce_label.setText(utils.duizhiLabelChange(predictLabel));
                yuce_score.setText(predictScore.toString());

                zhenchan_lable.setText(utils.zhenchanLabelChange(pred1ctLabe1));
                zhenchan_score.setText(String.valueOf(RTScore));
                pingju_score.setText(String.valueOf(PScore));
                xiangxia_score.setText(String.valueOf(PTScore));
                xiangnei_score.setText(String.valueOf(PTTScoreRTDisFea));

                jingzhi_jizhiduan.setText(utils.resChange((int) RTDisFea[0]));
                jingzhi_jiaodu.setText(String.valueOf(RTDisFea[1]) + " deg");
                jingzhi_pinglv.setText(String.valueOf(RTDisFea[2]) + " HZ");

                pingju_zhitiduan.setText(utils.resChange((int) PDisFea[0]));
                pingju_jiaodu.setText(String.valueOf(PDisFea[1]) + " deg");
                pingju_pinglv.setText(String.valueOf(PDisFea[2]) + " HZ");

                xiangxia_zhitiduan.setText(utils.resChange((int) PTDisFea[0]));
                xiangxia_jiaodu.setText(String.valueOf(PTDisFea[1]) + " deg");
                xiangxia_pinglv.setText(String.valueOf(PTDisFea[2]) + " HZ");

                xiangnei_zhitiduan.setText(utils.resChange((int) PTTDisFea[0]));
                xiangnei_jiaodu.setText(String.valueOf(PTTDisFea[1]) + " deg");
                xiangnei_pinglv.setText(String.valueOf(PTTDisFea[2]) + " HZ");
            }else{
                duizhi_jiaosudu.setText(duizhi_jiaosudu_strR + "rad/s");
                dakai_jiaosudu.setText(dakai_jiaosudu_strR + "rad/s");
                bihe_jiaosudu.setText(bihe_jiaosudu_strR + "rad/s");
                duizhi_cishu.setText(duizhi_cishu_strR + "次");
                yuce_label.setText(utils.duizhiLabelChange(predictLabelR));
                yuce_score.setText(predictScoreR.toString());

                zhenchan_lable.setText(utils.zhenchanLabelChange(pred1ctLabe1R));
                zhenchan_score.setText(String.valueOf(RTScoreR));
                pingju_score.setText(String.valueOf(PScoreR));
                xiangxia_score.setText(String.valueOf(PTScoreR));
                xiangnei_score.setText(String.valueOf(PTTScoreRTDisFeaR));

                jingzhi_jizhiduan.setText(utils.resChange((int) RTDisFeaR[0]));
                jingzhi_jiaodu.setText(String.valueOf(RTDisFeaR[1]) + " deg");
                jingzhi_pinglv.setText(String.valueOf(RTDisFeaR[2]) + " HZ");

                pingju_zhitiduan.setText(utils.resChange((int) PDisFeaR[0]));
                pingju_jiaodu.setText(String.valueOf(PDisFeaR[1]) + " deg");
                pingju_pinglv.setText(String.valueOf(PDisFeaR[2]) + " HZ");

                xiangxia_zhitiduan.setText(utils.resChange((int) PTDisFeaR[0]));
                xiangxia_jiaodu.setText(String.valueOf(PTDisFeaR[1]) + " deg");
                xiangxia_pinglv.setText(String.valueOf(PTDisFeaR[2]) + " HZ");

                xiangnei_zhitiduan.setText(utils.resChange((int) PTTDisFeaR[0]));
                xiangnei_jiaodu.setText(String.valueOf(PTTDisFeaR[1]) + " deg");
                xiangnei_pinglv.setText(String.valueOf(PTTDisFeaR[2]) + " HZ");
            }
        }
        if(isJiaozhun1==true && isJiaozhun2==true){
            loadingLayout.setVisibility(View.GONE);
            if(isSaveUserFileDone==false){
                saveUserFormFile(userName,userAge,userGender);
                isSaveUserFileDone=true;
            }
        }
    }
    // 处理返回箭头点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onStop() {
        super.onStop();
        if(conDeviceNum==1) {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
        }else {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
            processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
            processorManagerRight.setzero();
            processorManagerRight.stopProcessing();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(conDeviceNum==1) {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
        }else {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
            processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
            processorManagerRight.setzero();
            processorManagerRight.stopProcessing();
        }
    }
}